package org.seed.rpc.springboot;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Configuration
@EnableConfigurationProperties(EcRpcProperties.class)
public class EcRpcAutoConfiguration implements InitializingBean {

    private final EcRpcProperties ecRpcProperties;

    private ApplicationContext applicationContext;

    @Value("${spring.application.name}")
    private String serviceName;

    @Value("${eureka.client.service-url.defaultZone}")
    private String eurekaServiceUrl;

    @Value("${server.port}")
    private Integer port;


    public EcRpcAutoConfiguration(EcRpcProperties ecRpcProperties) {
        this.ecRpcProperties = ecRpcProperties;
        if (!StringUtils.hasText(ecRpcProperties.getServiceName())) {
            this.ecRpcProperties.setServiceName(serviceName);
        }
        if (!StringUtils.hasText(ecRpcProperties.getEurekaServiceUrl())) {
            this.ecRpcProperties.setEurekaServiceUrl(eurekaServiceUrl);
        }
        if (ecRpcProperties.getPort() == null || ecRpcProperties.getPort().intValue() < 128) {
            this.ecRpcProperties.setPort(port + 10);
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        EcRpcServerStarter.run(ecRpcProperties);
    }


}
